package com.jyxd.web.service.assessment.basic;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.jyxd.web.config.ConstantConfig;
import com.jyxd.web.dao.ZNurseRecordUpdateLog.ZNurseRecordUpdateLogDao;
import com.jyxd.web.dao.basic.MonitorLifeDataDao;
import com.jyxd.web.dao.basic.NurseRecordFormDao;
import com.jyxd.web.dao.basic.NurseRecordFormPipeLengthDao;
import com.jyxd.web.dao.basic.RespiratorDataDao;
import com.jyxd.web.dao.patient.PatientDao;
import com.jyxd.web.data.ZNurseRecordUpdateLog.ZNurseRecordUpdateLogEntity;
import com.jyxd.web.data.basic.*;
import com.jyxd.web.data.dto.*;
import com.jyxd.web.data.mongo.BreathProperty;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.data.patient.PatientCureEvent;
import com.jyxd.web.data.user.User;
import com.jyxd.web.error.JyxdException;
import com.jyxd.web.mq.HisViewProduction;
import com.jyxd.web.mq.TemperatureSheetSender;
import com.jyxd.web.service.hisview.dto.HisViewDataDto;
import com.jyxd.web.service.patient.IPatientCureEventService;
import com.jyxd.web.util.DateUtil;
import com.jyxd.web.util.PatientEvent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static com.jyxd.web.config.ConstantConfig.*;
import static com.jyxd.web.util.DateUtil.*;
import static com.jyxd.web.util.ExecuteUtil.*;
import static com.jyxd.web.util.MybatisPlusUtil.getParamOne;
import static com.jyxd.web.util.UUIDUtil.getUUID;
import static com.jyxd.web.util.VitalSignUtil.getIsOpenPulseRecord;
import static java.lang.Double.parseDouble;

/**
 * 三合一护理单service
 */
@Service
@Transactional
public class NurseRecordFormService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //护理单可批量修改的列
    public static final List<String> FIELD_LIST = Arrays.asList("consciousness","pupilSizeLeft","pupilSizeRight"
                                                                ,"pupilResponseLeft","pupilResponseRight","heartRhythm"
                                                                ,"oxygenMode","oxygenFlow","mode","fio2","vt","f","pinsp"
                                                                ,"ps","peep","ipap","epap","pipeNurse","nurseActivity"
                                                                ,"nurseMeasure","nurseSkin");

    @Autowired
    private NurseRecordFormPipeLengthDao nurseRecordFormPipeLengthDao;

    @Autowired
    private VitalSignMergeService vitalSignMergeService;
    @Autowired
    private NurseRecordFormDao nurseRecordFormDao;
    @Autowired
    private MonitorLifeDataDao monitorLifeDataDao;

    @Autowired
    private MonitorLifeDataService monitorLifeDataService;

    @Autowired
    private PatientDao patientDao;

    @Autowired
    private MedOrderExecRecordService medOrderExecRecordService;

    @Autowired
    private MedOrderExecService medOrderExecService;

    @Autowired
    private BloodSugarService bloodSugarService;

    @Autowired
    private AbpService abpService;

    @Autowired
    private RespiratorDataDao respiratorDataDao;

    @Autowired
    private HisViewProduction hisViewProduction;

    @Autowired
    private NurseRecordFormOutPutService nurseRecordFormOutPutService;
    @Autowired
    private NurseRecordFormPipeLengthService nurseRecordFormPipeLengthService;
    @Autowired
    private NursingTaskService nursingTaskService;
    @Autowired
    private TemperatureSheetSender temperatureSheetSender;
    @Autowired
    private MongodbService mongodbService;
    @Autowired
    private IPatientCureEventService patientCureEventService;

    @Resource
    private ZNurseRecordUpdateLogDao zNurseRecordUpdateLogDao;

    public int insert(NurseRecordForm nurseRecordForm) {
        return nurseRecordFormDao.insert(nurseRecordForm);
    }

    public boolean update(NurseRecordForm nurseRecordForm) {
        return nurseRecordFormDao.update(nurseRecordForm);
    }

    public NurseRecordForm queryData(String id) {
        return nurseRecordFormDao.queryData(id);
    }

    /**
     * 根据条件分页查询生命体征表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    public HttpResult queryList(Map<String, Object> map) {
        if (!map.containsKey("hour")) {
            return new HttpResult(200, "查询时间跨度小时为空，查询失败");
        }
        try {
            Date endTime = getLaterHoursDate(yyyyMMddHHmmssSdfToDate(String.valueOf(map.get("startTime"))), Long.valueOf(String.valueOf(map.get("hour"))));
            map.put("endTime", yyyyMMddHHmmssSdfToString(endTime));
            int totalCount = 0;
            if (map != null && map.containsKey("start")) {
                totalCount = queryNum(map);
                map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            }
            List<NurseRecordForm> list = nurseRecordFormDao.queryList(map);
            //if (list != null && list.size() > 0) {
            return new HttpResult(200, list, totalCount, "数据查询成功");
            //}
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new HttpResult(500, "数据查询失败");

    }

    /**
     * 获取有创血压的列表页面
     * * @param map
     *
     * @return
     */
    public HttpResult queryABPList(Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        if (map != null && map.containsKey("start")) {
            int totalCount = queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            double maxWeek = totalCount / (int) map.get("size");
            int maxWeek_ = (int) Math.ceil(maxWeek);
            resMap.put("maxWeek", maxWeek_);
        }
        List<NurseRecordForm> list = nurseRecordFormDao.queryList(map);
        NurseRecordForm entity = new NurseRecordForm();
        try {
            if (list != null && list.size() > 0) {
                if (list.size() < (int) map.get("size")) {
                    int count = (int) map.get("size") - list.size();
                    for (int i = 0; i < count; i++) {
                        list.add((NurseRecordForm) entity.clone());
                    }
                }
            } else {
                int count = (int) map.get("size");
                for (int i = 0; i < count; i++) {
                    list.add((NurseRecordForm) entity.clone());
                }
            }
            resMap.put("list", list);
            return new HttpResult(200, resMap, "数据查询成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HttpResult(200, resMap, "数据查询失败");
    }

    public int queryNum(Map<String, Object> map) {
        return nurseRecordFormDao.queryNum(map);
    }

    /**
     * 获取统计数据
     *
     * @param map
     * @param session
     * @return
     */
    public HttpResult inOutSummary(Map<String, Object> map, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            errorIfEmpty(user, "登录人不存在");
            errorIfEmpty(map, "参数不能为空");
            errorIfEmpty(map.get("patientId"), "请选择患者");
            errorIfEmpty(map.get("startTime"), "统计开始时间不能为空");
            errorIfEmpty(map.get("endTime"), "统计结束时间不能为空");
            errorIfEmpty(map.get("flag"), "统计标识不能为空");
            String flag = (String) map.get("flag");
            errorIfTrue(!StringUtils.equals(flag, "小结") && !StringUtils.equals(flag, "总结"), "flag值错误");
            Date startTime = yyyyMMddHHmmssSdfToDate((String) map.get("startTime"));
            Date endTime = yyyyMMddHHmmssSdfToDate((String) map.get("endTime"));
            //判断开始时间不等于7点的数据
            if (!"07:00:00".equals(map.get("startTime").toString().split(" ")[1])) {
                Date beforeHoursDate = DateUtil.getBeforeHoursDate(startTime, 1L);
                map.put("startTime", DateUtil.yyyyMMddHHmmssSdfToString(beforeHoursDate));
            }
            List<NurseRecordForm> nurseRecordFormList = nurseRecordFormDao.queryList(map);
            errorIfEmpty(nurseRecordFormList, "查询数据为空");
            nurseRecordFormList = getSummaryData(nurseRecordFormList, flag, startTime, endTime, user, map);
            return new HttpResult(200, nurseRecordFormList, "数据查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult(500, "统计发生错误，错误信息 - > " + e.getMessage());
        }
    }

    /**
     * 计算统计数据
     *
     * @param list
     * @param flag
     * @param startTime
     * @param enTime
     * @return
     */
    private List<NurseRecordForm> getSummaryData(List<NurseRecordForm> list, String flag, Date startTime, Date enTime, User user, Map<String, Object> paramMap) {
        NurseRecordForm nurseRecordFormCount = accumulationInitialize(flag, getSumTime(startTime, enTime));
        List<NurseRecordForm> nurseRecordFormList = list;
        list.forEach(nurseRecordForm -> {
            if (StringUtils.equals(nurseRecordForm.getFlag(), "小结") || StringUtils.equals(nurseRecordForm.getFlag(), "总结"))
                return;
            getCalculateNum(nurseRecordFormCount, nurseRecordForm, nurseRecordFormList);
        });
        // 赋值基本数据
        basicsAssignment(nurseRecordFormCount, list.get(0), enTime, user, paramMap);
        saveNurseRecordForm(nurseRecordFormCount);
        list.add(nurseRecordFormCount);
        return list;
    }

    /**
     * 获取其它字段内容
     *
     * @param paramMap
     * @return
     */
    private String getOtherOutNum(Map<String, Object> paramMap) {
        List<Map<String, Object>> list = nurseRecordFormDao.queryOutPutSum(paramMap);
        if (isEmpty(list))
            return null;
        StringBuffer str = new StringBuffer();
        list.forEach(map -> {
            if (isEmpty(map))
                return;
            if (isNotEmpty(map.get("outPutName")))
                str.append(map.get("outPutName")).append(":").append(map.get("outPutValue")).append("ml").append(";");
        });
        return str.toString();
    }

    /**
     * 新增总结小结数据到数据库
     *
     * @param nurseRecordForm
     */
    private void saveNurseRecordForm(NurseRecordForm nurseRecordForm) {
        Map<String, Object> map = new HashMap<>();
        map.put("patientId", nurseRecordForm.getPatientId());
        map.put("dataTime", yyyyMMddHHmmssSdfToString(nurseRecordForm.getDataTime()));
        map.put("flag", nurseRecordForm.getFlag());
        NurseRecordForm oldNurseRecordForm = nurseRecordFormDao.queryByPatientAndDataTime(map);
        if (Objects.nonNull(oldNurseRecordForm)) {
            oldNurseRecordForm.setStatus(-1);
            nurseRecordFormDao.update(oldNurseRecordForm);
        }
        nurseRecordFormDao.insert(nurseRecordForm);
    }

    /**
     * 获取累加值
     *
     * @param nurseRecordFormCount
     * @param nurseRecordForm
     * @return
     */
    private NurseRecordForm getCalculateNum(NurseRecordForm nurseRecordFormCount, NurseRecordForm nurseRecordForm, List<NurseRecordForm> nurseRecordFormList) {
        nurseRecordFormCount.setReserveAmount(add(nurseRecordFormCount.getReserveAmount(), getSurplusOrReserveAmountCount(nurseRecordForm, "reserveAmount", nurseRecordFormList).toString()).toString()); // 备用量
        nurseRecordFormCount.setPracticalAmount(add(nurseRecordFormCount.getPracticalAmount(), nurseRecordForm.getPracticalAmount()).toString()); // 实入量
        nurseRecordFormCount.setSurplus(add(nurseRecordFormCount.getSurplus(), getSurplusOrReserveAmountCount(nurseRecordForm, "surplus", nurseRecordFormList).toString()).toString()); // 余量
        nurseRecordFormCount.setUrine(add(nurseRecordFormCount.getUrine(), nurseRecordForm.getUrine()).toString()); // 尿量
        nurseRecordFormCount.setExcrement(add(nurseRecordFormCount.getExcrement(), nurseRecordForm.getExcrement()).toString()); // 大便
        //nurseRecordFormCount.setOtherOutNum(getNumKey(strToDouble(nurseRecordFormCount.getOtherOutNum()), getDoubleTotal(nurseRecordForm.getOtherOutNum()))); // 其它
        nurseRecordFormCount.setOutputAmount(add(nurseRecordFormCount.getOutputAmount(), nurseRecordForm.getOutputAmount()).toString()); // 总出量
        return nurseRecordFormCount;
    }

    private BigDecimal strToBigDecimal(String value){
        if(NumberUtil.isNumber(value)){
            return new BigDecimal(value);
        }
        return BigDecimal.ZERO;
    }

    private BigDecimal add(String a,String b){
        if(NumberUtil.isNumber(a) && NumberUtil.isNumber(b)){
            return new BigDecimal(a).add(new BigDecimal(b));
        }
        if(NumberUtil.isNumber(a)){
            return new BigDecimal(a);
        }
        if(NumberUtil.isNumber(b)){
            return new BigDecimal(b);
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取余量或备用量数据
     *
     * @param
     * @return
     */
    private BigDecimal getSurplusOrReserveAmountCount(NurseRecordForm nurseRecordForm, String flag, List<NurseRecordForm> nurseRecordFormList) {
        errorIfEmpty(nurseRecordForm, "出入量数据为空");
        errorIfEmpty(flag, "标识不能为空");
        String useSign = nurseRecordForm.getUseReuse();
        String parentId = nurseRecordForm.getParentId();
        String id = nurseRecordForm.getId();
        switch (flag) {
            case "surplus":
                //父id为空第一次添加数据，   判断id有没有被其他数据使用，即有没有2次沿用的数据，如果有，不计算
                if (isEmpty(parentId) && isExistThisParentId(nurseRecordFormList, id)) {
                    return BigDecimal.ZERO;
                }
                if (isNotEmpty(parentId)) {
                    //余量沿用的数据只要不在范围之内都算
                    //if (!isExistThisDataList(nurseRecordFormList, parentId) && StringUtils.contains(useSign, IN_OUT_AMOUNT_USE_SURPLUS))
                    //    return 0.0;
                    if (isExistThisParentId(nurseRecordFormList, id))
                        return BigDecimal.ZERO;
                }
                //logger.error(id+"余量id");
                return strToBigDecimal(nurseRecordForm.getSurplus());
            case "reserveAmount":
                if (org.apache.commons.lang.StringUtils.isNotEmpty(useSign) && (org.apache.commons.lang.StringUtils.contains(useSign, IN_OUT_AMOUNT_ALL_ALLOWANCE_DOSAGE) && isExistThisDataList(nurseRecordFormList, parentId)))
                    return BigDecimal.ZERO;
                if (org.apache.commons.lang.StringUtils.isNotEmpty(useSign) && (org.apache.commons.lang.StringUtils.contains(useSign, IN_OUT_AMOUNT_ALL_ALLOWANCE_DOSAGE) && isExistThisDataList(nurseRecordFormList, parentId)))
                    return BigDecimal.ZERO;
                //logger.error(id+"备用量id");
                return strToBigDecimal(nurseRecordForm.getReserveAmount());
            default:
                return BigDecimal.ZERO;
        }
    }

    /**
     * 判断总结是否需要总结数据
     *
     * @param
     * @return
     */
    private boolean isExistThisDataList(List<NurseRecordForm> nurseRecordFormList, String parentId) {
        if (isEmpty(nurseRecordFormList))
            return false;
        if (isEmpty(parentId))
            return false;
        AtomicBoolean isExist = new AtomicBoolean(false);
        nurseRecordFormList.forEach(nurseRecordForm -> {
            if (isNotEmpty(nurseRecordForm.getId()) && StringUtils.equals(nurseRecordForm.getId(), parentId))
                isExist.set(true);
        });
        return isExist.get();
    }

    /**
     * 判断id是否存在parentId
     *
     * @param
     * @return
     */
    private boolean isExistThisParentId(List<NurseRecordForm> nurseRecordFormList, String id) {
        if (isEmpty(nurseRecordFormList))
            return false;
        if (isEmpty(id))
            return false;
        AtomicBoolean isExist = new AtomicBoolean(false);
        nurseRecordFormList.forEach(nurseRecordForm -> {
            if (isNotEmpty(nurseRecordForm.getParentId()) && StringUtils.equals(nurseRecordForm.getParentId(), id))
                isExist.set(true);
        });
        return isExist.get();
    }


    /**
     * 计算总出量
     *
     * @param nurseRecordForm
     * @return
     */
    public BigDecimal calculateOutputAmount(NurseRecordForm nurseRecordForm) {
        if (Objects.isNull(nurseRecordForm))
            return BigDecimal.ZERO;
        // 总出量等于尿量 + 大便 + 其它
        BigDecimal otherOutNum = BigDecimal.ZERO;
        if(Objects.nonNull(nurseRecordForm.getNurseRecordFormDto())){
            NurseRecordFormDTO nurseRecordFormDto = nurseRecordForm.getNurseRecordFormDto();
            if(CollectionUtil.isNotEmpty(nurseRecordFormDto.getList())){
                List<NurseRecordFormOutPut> list = nurseRecordFormDto.getList();
                otherOutNum = list.stream().map(NurseRecordFormOutPut::getOutPutValue).filter(str ->NumberUtil.isNumber(str))
                        .map(BigDecimal::new)
                        .reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            }
        }
        return strToBigDecimal(nurseRecordForm.getUrine()).add(strToBigDecimal(nurseRecordForm.getExcrement())).add(otherOutNum);
    }

    /**
     * 数据转double
     *
     * @param value
     * @return
     */
    private Double strToDouble(String value) {
        if (StringUtils.isEmpty(value))
            return 0.0;
        if (StringUtils.equals(value, "null"))
            return 0.0;
        if (StringUtils.equals(value, ""))
            return 0.0;
        try {
            return parseDouble(value);
        } catch (Exception e) {
            logger.info("统计计算错误，转换数值失败");
            return 0.0;
        }
    }

    /**
     * 计算累加值
     *
     * @param initialValue
     * @param value
     * @return
     */
    private String getNumKey(Object initialValue, Double value) {
        if (Objects.isNull(initialValue) || Objects.isNull(value))
            return "0.0";
        return String.valueOf((Double) initialValue + value);
    }


    /**
     * 初始化原始参数
     *
     * @return
     */
    private NurseRecordForm accumulationInitialize(String flag, String describe) {
        NurseRecordForm nurseRecordForm = new NurseRecordForm();
        nurseRecordForm.setReserveAmount("0.0"); // 备用量
        nurseRecordForm.setPracticalAmount("0.0"); // 实入量
        nurseRecordForm.setSurplus("0.0"); // 余量
        nurseRecordForm.setUrine("0.0"); // 尿量
        nurseRecordForm.setExcrement("0.0"); // 大便
        nurseRecordForm.setOtherOutNum("0.0"); // 其它
        nurseRecordForm.setOutputAmount("0.0"); // 总出量
        nurseRecordForm.setFlag(flag);
        if (StringUtils.equals(flag, "小结"))
            nurseRecordForm.setMedicineContent(describe + "小结");
        if (StringUtils.equals(flag, "总结"))
            nurseRecordForm.setMedicineContent(describe + "总结");
        return nurseRecordForm;
    }

    /**
     * 基础数据赋值
     *
     * @param newNurseRecordForm
     * @param oldNurseRecordForm
     * @return
     */
    private void basicsAssignment(NurseRecordForm newNurseRecordForm, NurseRecordForm oldNurseRecordForm, Date dataTime, User user, Map<String, Object> paramMap) {
        newNurseRecordForm.setId(getUUID());
        newNurseRecordForm.setCreateTime(new Date());
        newNurseRecordForm.setDataTime(dataTime);
        newNurseRecordForm.setVisitCode(oldNurseRecordForm.getVisitCode());
        newNurseRecordForm.setVisitId(oldNurseRecordForm.getVisitId());
        newNurseRecordForm.setPatientId(oldNurseRecordForm.getPatientId());
        newNurseRecordForm.setOperatorCode(user.getWorkNumber());
        newNurseRecordForm.setOperatorName(user.getUserName());
        newNurseRecordForm.setStatus(1);
        newNurseRecordForm.setOtherOutNum(getOtherOutNum(paramMap));
    }


    /**
     * 新增或者修改生命体征三合一表
     *
     * @param nurseRecordForm
     * @param session
     * @return
     */
    public HttpResult saveOrUpdateData(NurseRecordForm nurseRecordForm, HttpSession session) {
//        if(nurseRecordForm == null || StringUtils.isEmpty(nurseRecordForm.getPatientId())){
//            return new HttpResult(500,"系统错误");
//        }
        Patient patient = patientDao.queryData(nurseRecordForm.getPatientId());
        User user = (User) session.getAttribute("user");
        //        if(user == null || StringUtils.isEmpty(user.getRoleId())){
//            return new HttpResult(500,"系统错误");
//        }
//
//        Role role = roleDao.queryData(user.getRoleId());
//        if(role == null || !StringUtils.containsAny(role.getRoleName(),"超级管理员","护士长")){
//            if(patient == null || 1 != patient.getStatus()||  1 != patient.getFlag()){
//                return new HttpResult(500,"数据保存失败,患者已出科");
//            }
//        }
        if (Objects.nonNull(nurseRecordForm.getId()) && nurseRecordForm.getId() != "") {
            NurseRecordForm nurseRecordFormOld = nurseRecordFormDao.queryData(nurseRecordForm.getId());
            nurseRecordForm.setCreateTime(nurseRecordFormOld.getCreateTime());
            nurseRecordForm.setOrderCode(nurseRecordFormOld.getOrderCode());
            if(nurseRecordFormOld.getDataSource()!=0){
                buildAndSave(nurseRecordForm,patient,user,0);
                savePatientCureEvent(user,nurseRecordForm,patient);
            } else {
                nurseRecordForm.setUpdateTime(new Date());
                nurseRecordForm.setOperatorCodeUpdate(user.getWorkNumber());
                nurseRecordForm.setOperatorCodeUpdateName(user.getUserName());
                nurseRecordForm.setOutputAmount(String.valueOf(calculateOutputAmount(nurseRecordForm)));
                /**
                 *  修改医嘱执行次数
                 */
                updateMedOrderExecRecord(nurseRecordForm, user);

                nurseRecordForm.setOrderCode(nurseRecordForm.getOrderId());

                update(nurseRecordForm);
                logger.info("********&*******1:{}",nurseRecordForm.getId());
                saveNurseRecordFormOutPut(nurseRecordForm);

                // 记录修改日志
                ZNurseRecordUpdateLogEntity zNurseRecordUpdateLogEntity = new ZNurseRecordUpdateLogEntity();
                zNurseRecordUpdateLogEntity.setUpdateJson(JSON.toJSONString(nurseRecordFormOld));
                zNurseRecordUpdateLogEntity.setUserId(user.getId());
                zNurseRecordUpdateLogEntity.setUserName(user.getUserName());
                zNurseRecordUpdateLogEntity.setNurId(nurseRecordFormOld.getId());
                zNurseRecordUpdateLogDao.insert(zNurseRecordUpdateLogEntity);
            }
        } else {
            buildAndSave(nurseRecordForm,patient,user,0);
            savePatientCureEvent(user,nurseRecordForm,patient);
        }

        temperatureSheetSender.send(nurseRecordForm);
        // 新增生命体征时，新增无创血压单或血糖单
        syncNurseRecordFormArts(nurseRecordForm);
        syncNurseRecordFormBloodGlucose(nurseRecordForm);
        syncVitalSignMerge(nurseRecordForm);

        //TODO 数据中心暂时注释
        // 新增生命体征时，新增数据到数据中心
        hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HlLCZJL_BZBWHL, patient, nurseRecordForm));
        // 修改时生命体征时，新增护理观察数据到数据中心
        hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HLCZJL_BZBWHL_HLGC, nurseRecordForm));
        // 修改时生命体征时，新增体征记录数据到数据中心
        hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_ICU_DAT_TZJL, nurseRecordForm));
        return new HttpResult(200, nurseRecordForm,"数据新增成功");
    }

    private void syncVitalSignMerge(NurseRecordForm nurseRecordForm) {
        vitalSignMergeService.syncVitalSignMerge(nurseRecordForm);
    }

    private void savePatientCureEvent(User user, NurseRecordForm nurseRecordForm, Patient patient) {
        List<NurseRecordFormPipeLength> pipeLengthList = nurseRecordForm.getNurseRecordFormDto().getPipeLengthList();
        long time = nurseRecordForm.getDataTime().getTime();
        List<PatientCureEvent> list = new ArrayList<>();
        //插管事件
        if(!CollectionUtil.isEmpty(pipeLengthList)){
            pipeLengthList.forEach(pipeLength->{
                if(StringUtils.isNotBlank(pipeLength.getPipeName())){
                    PatientCureEvent cureEvent = new PatientCureEvent();
                    cureEvent.setId(getUUID());
                    cureEvent.setEventDate(Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).toLocalDateTime());
                    cureEvent.setUserId(user.getId());
                    cureEvent.setEventCode(PatientEvent.INTUBATE.getCode());
                    cureEvent.setName(pipeLength.getPipeName());
                    cureEvent.setDataSource(1);
                    cureEvent.setCreateTime(LocalDateTime.now());
                    cureEvent.setVisitId(patient.getVisitId());
                    cureEvent.setVisitCode(patient.getVisitCode());
                    cureEvent.setPatientId(patient.getId());
                    list.add(cureEvent);
                }
            });
        }

        if(StringUtils.isNotBlank(nurseRecordForm.getMode())){
            //呼吸模式事件  判断跟上次呼吸模式是否有变化
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("patientId", patient.getId());
            paramMap.put("endTime", DateUtil.yyyyMMddHHmmssSdfToString(nurseRecordForm.getDataTime()));
            paramMap.put("flag", "flag");
            paramMap.put("mode", "mode");
            //查询是否交班，交班返回空
            NurseRecordForm last = nurseRecordFormDao.queryByPatientAndDataTime(paramMap);
            if(Objects.isNull(last) || (StringUtils.isNotBlank(last.getMode()) && !StringUtils.equals(nurseRecordForm.getMode(),last.getMode()))){
                PatientCureEvent cureEvent = new PatientCureEvent();
                cureEvent.setId(getUUID());
                cureEvent.setEventDate(Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).toLocalDateTime());
                cureEvent.setUserId(user.getId());
                cureEvent.setEventCode(PatientEvent.MODE.getCode());
                cureEvent.setName(nurseRecordForm.getMode());
                cureEvent.setDataSource(1);
                cureEvent.setCreateTime(LocalDateTime.now());
                cureEvent.setVisitId(patient.getVisitId());
                cureEvent.setVisitCode(patient.getVisitCode());
                cureEvent.setPatientId(patient.getId());
                list.add(cureEvent);
            }
        }

        if(CollectionUtil.isNotEmpty(list)){
            patientCureEventService.saveBatch(list);
        }
    }

    private void buildAndSave(NurseRecordForm nurseRecordForm,Patient patient,User user,int dataSource){
        nurseRecordForm = newNurseRecordForm(nurseRecordForm, patient, null);
        nurseRecordForm.setId(getUUID());
        nurseRecordForm = setNurseRecordFormContent(nurseRecordForm, patient);
        nurseRecordForm.setOutputAmount(String.valueOf(calculateOutputAmount(nurseRecordForm)));
        /**
         *  修改医嘱执行次数
         */
        updateMedOrderExecRecord(nurseRecordForm, user);

        nurseRecordForm.setOrderCode(nurseRecordForm.getOrderId());
        nurseRecordForm.setDataSource(dataSource);

        if(user != null) {
            nurseRecordForm.setOperatorCode(user.getWorkNumber());
            nurseRecordForm.setOperatorName(user.getUserName());
        }
        insert(nurseRecordForm);
        logger.info("********&*******2:{}",nurseRecordForm.getId());
        nurseRecordForm.getNurseRecordFormDto().setRowId(nurseRecordForm.getId());
        saveNurseRecordFormOutPut(nurseRecordForm);
    }

    /**
     * 在护理单业务中处理医嘱同步状态，并添加医嘱次数子表
     * @param nurseRecordForm
     * @param user
     */
    private void updateMedOrderExecRecord(NurseRecordForm nurseRecordForm, User user) {
        if (isNotEmpty(nurseRecordForm.getOrderId()) && isNotEmpty(nurseRecordForm.getOrderTime())) {
            //添加医嘱的多次同步
            List<String> ordersList = new ArrayList<>();
            if (nurseRecordForm.getOrderId().contains(",")) {
                String[] orders = nurseRecordForm.getOrderId().split(",");
                ordersList = new ArrayList(Arrays.asList(orders));
            } else {
                ordersList.add(nurseRecordForm.getOrderId());
            }

            List<MedOrderExec> list = medOrderExecService.queryListByOrderIds(ordersList);
            //处理医嘱同步状态
            List<String> orderIdslist=new ArrayList<String>();

            for (MedOrderExec medOrderExec : list) {
                List<MedOrderExec> medOrderExecsList = medOrderExecService.queryDataByOrderSubNo(medOrderExec);
                for (MedOrderExec orderExec : medOrderExecsList) {
                    orderIdslist.add(orderExec.getId());
                    orderExec.setIsSync(1);//修改副医嘱的同步状态
                    medOrderExec.setRecentSyncTime(new Date());//最新同步时间
                    medOrderExec.setUpdateTime(new Date());
                    medOrderExec.setNurseCode(user.getLoginName());
                    medOrderExecService.update(orderExec);
                }
            }
            medOrderExecService.orderRecord(nurseRecordForm.getOrderId(), user, nurseRecordForm.getOrderTime());
        }
    }

    private void saveNurseRecordFormOutPut(NurseRecordForm nurseRecordForm) {
        if (isEmpty(nurseRecordForm))
            return;
        if (isEmpty(nurseRecordForm.getNurseRecordFormDto()))
            return;
        NurseRecordFormDTO nurseRecordFormDto = nurseRecordForm.getNurseRecordFormDto();
        if (isEmpty(nurseRecordFormDto.getPatientId()))
            nurseRecordFormDto.setPatientId(nurseRecordForm.getPatientId());
        if (isEmpty(nurseRecordFormDto.getRowId()))
            nurseRecordFormDto.setRowId(nurseRecordForm.getId());

        logger.info("********&*******3:{}",nurseRecordFormDto.getRowId());
        nurseRecordFormOutPutService.saveOrUpdate(nurseRecordFormDto);

        nurseRecordFormPipeLengthService.saveOrUpdate(nurseRecordFormDto);
    }

    /**
     * 删除生命体征表记录
     *
     * @param nurseRecordForm
     * @return
     */
    public HttpResult delete(NurseRecordForm nurseRecordForm, HttpSession session) {
//        if(nurseRecordForm == null || StringUtils.isEmpty(nurseRecordForm.getId())){
//            return new HttpResult(500,"系统错误");
//        }
//        NurseRecordForm fromDb = nurseRecordFormDao.queryData(nurseRecordForm.getId());
//        if(fromDb==null || StringUtils.isEmpty(fromDb.getPatientId())){
//            return new HttpResult(500,"系统错误");
//        }
//
//        User user = (User) session.getAttribute("user");
//        if(user == null || StringUtils.isEmpty(user.getRoleId())){
//            return new HttpResult(500,"系统错误");
//        }
//
//        Role role = roleDao.queryData(user.getRoleId());
//        if(role == null || !StringUtils.containsAny(role.getRoleName(),"超级管理员","护士长")){
//            Patient patient = patientDao.queryData(fromDb.getPatientId());
//            if(patient == null || 1 != patient.getStatus()||  1 != patient.getFlag()){
//                return new HttpResult(500,"数据删除失败,患者已出科");
//            }
//        }

        if (nurseRecordForm.getId() != null && !"".equals(nurseRecordForm.getId())) {
            if (Objects.nonNull(nurseRecordFormDao.queryByParentId(nurseRecordForm.getId()))) {
                return new HttpResult(500, "有沿用数据为删除，此数据不可删除，请删除沿用数据后再删除");
            }

            NurseRecordForm nurseRecordFormNew = queryData(nurseRecordForm.getId());
            if (nurseRecordFormNew != null) {
                nurseRecordFormNew.setStatus(-1);
                update(nurseRecordFormNew);
                bloodSugarService.deleteByRelevancyId(nurseRecordFormNew.getId());
                abpService.deleteByRelevancyId(nurseRecordFormNew.getId());
                nurseRecordFormOutPutService.updateByPatientIdAndRowId(nurseRecordForm.getPatientId(), nurseRecordForm.getId());
                nurseRecordFormPipeLengthService.updateByPatientIdAndRowId(nurseRecordForm.getPatientId(), nurseRecordForm.getId());
                //清空上一条记录的状态
                if (nurseRecordFormNew.getParentId() != null && !"".equals(nurseRecordFormNew.getParentId())) {
                    NurseRecordForm nurseRecordFormParent = queryData(nurseRecordFormNew.getParentId());
                    String medicineContent = nurseRecordFormParent.getMedicineContent();//()(
                    nurseRecordFormParent.setMedicineContent(medicineContent == null ? "" : medicineContent.replaceAll("(已沿用)", "").replaceAll("\\(", "").replaceAll("\\)", ""));
                    if (nurseRecordFormParent.getParentId() != null && !"".equals(nurseRecordFormParent.getParentId())) {
                        nurseRecordFormParent.setUseReuse(ConstantConfig.IN_OUT_AMOUNT_USE_ALL_ALLOWANCE_DOSAGE);
                    } else {
                        nurseRecordFormParent.setUseReuse(null);
                    }

                    update(nurseRecordFormParent);
                }
                return new HttpResult(200, "数据删除成功");
            } else {
                return new HttpResult(200, "无此数据");
            }
        }
        return new HttpResult(500, "系统错误");
    }


    /**
     * 同步到新的三合一生命体征表单
     *
     * @param patient
     * @param time
     * @param monitorLifeData
     * @param user
     * @throws ParseException
     */
    public HttpResult saveNurseRecordFormData(Patient patient, String time, MonitorLifeData monitorLifeData, User user) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        map.put("patientId", patient.getId());
        map.put("dataTime", time);
        map.put("dataSource", 1);
        boolean isOpenPulseRecord = getIsOpenPulseRecord(patient);
        NurseRecordForm nurseRecordForm = nurseRecordFormDao.queryByPatientAndDataTime(map);
        if (Objects.isNull(nurseRecordForm))
            newSaveNurseRecord(patient, yyyyMMddHHmmSdfToDate(time), monitorLifeData, isOpenPulseRecord, user);
        else
            // 赋值更新监护仪体征数据
            updateOldNurseRecordFormData(nurseRecordForm, monitorLifeData, isOpenPulseRecord, user, patient);
        return new HttpResult(200, "监护仪同步数据成功");
    }

    /**
     * 更新旧的数据
     */
    private void updateOldNurseRecordFormData(NurseRecordForm nurseRecordForm, MonitorLifeData monitorLifeData,
                                              boolean isOpenPulseRecord, User user, Patient patient) throws ParseException {
        // 赋值生命体征监护仪数据
        setNurseRecordForm(nurseRecordForm, monitorLifeData, isOpenPulseRecord, user);
        // 赋值最新的无变化数据
        setOldInvariantNurseRecordFormData(nurseRecordForm, nurseRecordForm.getDataTime(), 1);
        // 赋值生命体征呼吸机数据 todo 呼吸机暂时未接入
        // syncModeData(vitalSignMerge.getDataTime(), vitalSignMerge.getPatientId(), vitalSignMerge);
        update(nurseRecordForm);
        // 自动同步生命体征时，新增无创血压单
        syncNurseRecordFormArts(nurseRecordForm);
        // 自动同步时时，新增数据到数据中心
        // hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HlLCZJL_BZBWHL, patient, vitalSignMerge));
        // 自动同步生命体征时，新增体征记录数据到数据中心
        //  hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_ICU_DAT_TZJL, patient, vitalSignMerge));
    }

    private void newSaveNurseRecord(Patient patient, Date time, MonitorLifeData monitorLifeData, boolean isOpenPulseRecord, User user) {

        NurseRecordForm nurseRecordForm = newNurseRecordForm(null, patient, time);
        // 赋值监护仪体征数据
        setNurseRecordForm(nurseRecordForm, monitorLifeData, isOpenPulseRecord, user);
        // 赋值最新的无变化数据
        setOldInvariantNurseRecordFormData(nurseRecordForm, time, 1);
        // 赋值呼吸机数据 todo 呼吸机暂时未接入
        // syncModeData(vitalSignMerge.getDataTime(), vitalSignMerge.getPatientId(), vitalSignMerge);
        // 自动同步生命体征时，新增无创血压单
        syncNurseRecordFormArts(nurseRecordForm);
        //TODO 数据中心相关暂时注释
       /* // 自动同步生命体征时，新增到数据中心
        hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HlLCZJL_BZBWHL, patient, nurseRecordForm));
        // 自动同步生命体征时，新增体征记录数据到数据中心
        hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_ICU_DAT_TZJL, patient, nurseRecordForm));*/
        nurseRecordForm.setDataSource(1);
        setBreathProperty(nurseRecordForm,patient);
        nurseRecordFormDao.insert(nurseRecordForm);
    }

    /**
     * 赋值旧的不变的数据
     */
    private void setOldInvariantNurseRecordFormData(NurseRecordForm nurseRecordForm, Date time, int flag) {
        Map<String, Object> map = new HashMap<>();
        map.put("patientId", nurseRecordForm.getPatientId());
        map.put("endTime", DateUtil.yyyyMMddHHmmssSdfToString(time));
        /**
         * 添加限制条件，整点数据1小时之前进行赋值，非整点数据不赋值
         */
        NurseRecordForm oldNurseRecordForm = null;
        if (ConstantConfig.WHOLE_POINT_FLAG) {
            Date startTime = DateUtil.getLaterMinuteDate(time, -60L);
            String startTimeStr = DateUtil.yyyyMMddHHmmssSdfToString(startTime);
            map.put("startTime", startTimeStr);
            oldNurseRecordForm = nurseRecordFormDao.queryByPatientIdAndTimeData(map);
        } else {
            //兼容之前的逻辑
            oldNurseRecordForm = nurseRecordFormDao.queryByPatientIdNewData(map);
        }
        if (Objects.isNull(oldNurseRecordForm))
            return;
        //if (!DateUtil.wholePointFlag(DateUtil.yyyyMMddHHmmssSdfToString(time))) {
        //    return;
       // }
        if(oldNurseRecordForm!=null)
        //时间改变时需要判断数据是否有值，有值不更新,没值填充
            nurseRecordForm.setConsciousness(oldNurseRecordForm.getConsciousness()==null?"":oldNurseRecordForm.getConsciousness()); // 意识
            nurseRecordForm.setPupilSizeLeft(oldNurseRecordForm.getPupilSizeLeft()==null?"":oldNurseRecordForm.getPupilSizeLeft()); // 瞳孔大小左
            nurseRecordForm.setPupilSizeRight(oldNurseRecordForm.getPupilSizeRight()==null?"":oldNurseRecordForm.getPupilSizeRight());// 瞳孔大小右
            nurseRecordForm.setPupilResponseLeft(oldNurseRecordForm.getPupilResponseLeft()==null?"":oldNurseRecordForm.getPupilResponseLeft()); // 瞳孔反应左
            nurseRecordForm.setPupilResponseRight(oldNurseRecordForm.getPupilResponseRight()==null?"":oldNurseRecordForm.getPupilResponseRight()); // 瞳孔反应右
            nurseRecordForm.setHeartRhythm(oldNurseRecordForm.getHeartRhythm()==null?"":oldNurseRecordForm.getHeartRhythm()); // 心律

            nurseRecordForm.setOxygenMode(oldNurseRecordForm.getOxygenMode()==null?"":oldNurseRecordForm.getOxygenMode()); // 吸氧方式
            nurseRecordForm.setFio2(oldNurseRecordForm.getFio2()==null?"":oldNurseRecordForm.getFio2()); // fio2
            nurseRecordForm.setOxygenFlow(oldNurseRecordForm.getOxygenFlow()==null?"":oldNurseRecordForm.getOxygenFlow()); // 氧流量
            /**
             * 同步生命体征添加模式机参数
             */
            nurseRecordForm.setMode(oldNurseRecordForm.getMode()==null?"":oldNurseRecordForm.getMode());
            nurseRecordForm.setVt(oldNurseRecordForm.getVt()==null?"":oldNurseRecordForm.getVt());
            nurseRecordForm.setF(oldNurseRecordForm.getF()==null?"":oldNurseRecordForm.getF());
            nurseRecordForm.setPinsp(oldNurseRecordForm.getPinsp()==null?"":oldNurseRecordForm.getPinsp());
            nurseRecordForm.setPs(oldNurseRecordForm.getPs()==null?"":oldNurseRecordForm.getPs());
            nurseRecordForm.setPeep(oldNurseRecordForm.getPeep()==null?"":oldNurseRecordForm.getPeep());
            nurseRecordForm.setIpap(oldNurseRecordForm.getIpap()==null?"":oldNurseRecordForm.getIpap());
            nurseRecordForm.setEpap(oldNurseRecordForm.getEpap()==null?"":oldNurseRecordForm.getEpap());
            nurseRecordForm.setPipeNurse(oldNurseRecordForm.getPipeNurse()==null?"":oldNurseRecordForm.getPipeNurse()); // 导管/护理
        //nurseRecordForm.setNurseMeasure(oldNurseRecordForm.getNurseMeasure()); //  护理措施
        // nurseRecordForm.setNurseSkin(oldNurseRecordForm.getNurseSkin()); //护理皮肤
        //if (StringUtils.isNotEmpty(oldNurseRecordForm.getSecondSign()))  // 赋值签名 ， 如果有接班签名则获取上一条签名，否则赋值旧的签名
        //   nurseRecordForm.setSign(oldNurseRecordForm.getSecondSign());
        //else
        //   nurseRecordForm.setSign(oldNurseRecordForm.getSign());

        //去除相关插入导管数据表 不自动延续
        /**
         Map<String, Object> mapLength = new HashMap<>();
         map.put("row_id", oldNurseRecordForm.getId());
         map.put("patient_id", oldNurseRecordForm.getPatientId());
         List<NurseRecordFormPipeLength> list = nurseRecordFormPipeLengthService.selectByPatientIdAndRowId(oldNurseRecordForm.getPatientId(),oldNurseRecordForm.getId());
         if(list!=null && list.size()>0){
         for (NurseRecordFormPipeLength nurseRecordFormPipeLength : list) {
         nurseRecordFormPipeLength.setId(getUUID());
         nurseRecordFormPipeLength.setCreateTime(new Date());
         nurseRecordFormPipeLength.setRowId(nurseRecordForm.getId());;
         nurseRecordFormPipeLengthDao.insert(nurseRecordFormPipeLength);
         }
         }
         **/
        //赋值自动签名的数据
        //双签名赋值第2个签名
        if(oldNurseRecordForm.getSign()!=null && !"".equals(oldNurseRecordForm.getSign()) && oldNurseRecordForm.getSecondSign()!=null && !"".equals(oldNurseRecordForm.getSecondSign())){
            nurseRecordForm.setSign(oldNurseRecordForm.getSecondSign());
        }else if(oldNurseRecordForm.getSign()!=null && !"".equals(oldNurseRecordForm.getSign()) && (oldNurseRecordForm.getSecondSign()==null || "".equals(oldNurseRecordForm.getSecondSign()))){
            //单签名赋值第1个签名
            nurseRecordForm.setSign(oldNurseRecordForm.getSign());
        }
    }

    /**
     * 赋值监护仪数据到生命体征表
     *
     * @param nurseRecordForm
     * @param monitorLifeData
     */
    private void setNurseRecordForm(NurseRecordForm nurseRecordForm, MonitorLifeData monitorLifeData,
                                    boolean isOpenPulseRecord, User user) {
        if (StringUtils.isNotEmpty(monitorLifeData.getTemp()))
            nurseRecordForm.setTemplate(monitorLifeData.getTemp()); // 赋值体温
        if (StringUtils.isNotEmpty(monitorLifeData.getHr()))
            nurseRecordForm.setHr(monitorLifeData.getHr()); // 赋值心率
        if (StringUtils.isNotEmpty(monitorLifeData.getPulse()) && isOpenPulseRecord)
            nurseRecordForm.setPulse(monitorLifeData.getPulse()); //赋值脉搏
        if (StringUtils.isNotEmpty(monitorLifeData.getResp()))
            nurseRecordForm.setBr(monitorLifeData.getResp()); //赋值呼吸
        if (StringUtils.isNotEmpty(monitorLifeData.getNibps()) && StringUtils.isNotEmpty(monitorLifeData.getNibpd()))
            nurseRecordForm.setNbp(monitorLifeData.getNibps() + "/" + monitorLifeData.getNibpd()); // 赋值无创血压
        if (StringUtils.isNotEmpty(monitorLifeData.getArts()) && StringUtils.isNotEmpty(monitorLifeData.getArtd()))
            nurseRecordForm.setAbp(monitorLifeData.getArts() + "/" + monitorLifeData.getArtd()); // 赋值有创血压
        if (StringUtils.isNotEmpty(monitorLifeData.getSpo2()))
            nurseRecordForm.setSpO2(monitorLifeData.getSpo2()); //赋值血氧饱和
        if (Objects.nonNull(user)) {
            nurseRecordForm.setOperatorCode(user.getId());
            nurseRecordForm.setOperatorName(user.getUserName());
            nurseRecordForm.setSign(user.getUserName());
        }
    }

    /**
     * 生成新的生命体征三合一数据
     *
     * @param nurseRecordForm
     * @param patient
     * @param time
     * @return
     */
    private NurseRecordForm newNurseRecordForm(NurseRecordForm nurseRecordForm, Patient patient, Date time) {
        if (Objects.isNull(nurseRecordForm) || StringUtils.isEmpty(nurseRecordForm.getId())) {
            if (Objects.isNull(nurseRecordForm))
                nurseRecordForm = new NurseRecordForm();
            nurseRecordForm.setId(getUUID());
            nurseRecordForm.setCreateTime(new Date());
            nurseRecordForm.setUpdateTime(new Date());
            nurseRecordForm.setStatus(1);
        }
        nurseRecordForm.setPatientId(patient.getId());
        nurseRecordForm.setVisitCode(patient.getVisitCode());
        nurseRecordForm.setVisitId(patient.getVisitId());
        if (Objects.nonNull(time))
            nurseRecordForm.setDataTime(time);
        return nurseRecordForm;
    }

    public void syncNurseRecordFormArts(NurseRecordForm nursingRecord) {
        errorIfEmpty(nursingRecord, "生命体征数据为空");
        if (Objects.isNull(nursingRecord.getAbp()) || nursingRecord.getAbp() == "" || nursingRecord.getAbp() == "null/null")
            return;
        abpService.saveOrUpdate(new BaseDataDto(nursingRecord.getPatientId(), nursingRecord.getId(), nursingRecord.getAbp(),
                nursingRecord.getDataTime(), nursingRecord.getSign()));
    }

    /**
     * 自动同步血糖数据到血糖单
     *
     * @param
     */
    public void syncNurseRecordFormBloodGlucose(NurseRecordForm nursingRecord) {
        errorIfEmpty(nursingRecord, "生命体征数据为空");
        if (Objects.isNull(nursingRecord.getBloodGlucose()) || nursingRecord.getBloodGlucose() == "")
            return;
        bloodSugarService.saveOrUpdate(new BaseDataDto(nursingRecord.getPatientId(), nursingRecord.getId(), nursingRecord.getBloodGlucose(),
                nursingRecord.getDataTime(), nursingRecord.getSign()));
    }

    private NurseRecordForm setNurseRecordFormContent(NurseRecordForm nurseRecordForm, Patient patient) {
        return (NurseRecordForm) monitorLifeDataService.setObjectMonitorLifeData(patient, yyyyMMddHHmmssSdfToString(nurseRecordForm.getDataTime()), nurseRecordForm);
    }

    /**
     * 三表合一余量沿用
     *
     * @return
     */
    public HttpResult getResidualUseById(NurseRecordForm nurseRecordForm, HttpSession session) throws ParseException {
        User user = (User) session.getAttribute("user");
        errorIfEmpty(nurseRecordForm, "参数为空");
        errorIfEmpty(nurseRecordForm.getId(), "id为空");
        errorIfEmpty(nurseRecordForm.getDataTime(), "时间为空");
        if(nurseRecordForm.getDataTime().compareTo(new Date())>0){
            throw new JyxdException("沿用时间大于当前时间不能录入,请修改沿用时间！");
        }
        //根据ID查询表
        NurseRecordForm oldNurseRecordForm = queryData(nurseRecordForm.getId());
        //是否存在
        if (Objects.isNull(oldNurseRecordForm))
            return new HttpResult(500, "查询数据为空");
        // 查询是否存在旧的沿用数据
        if (Objects.nonNull(nurseRecordFormDao.queryByParentId(nurseRecordForm.getId())))
            return new HttpResult(500, "已存在旧的沿用数据，请删除后再次沿用");
        //余量是否为空
        if (StringUtils.isEmpty(oldNurseRecordForm.getSurplus()))
            return new HttpResult(500, "查询余量为空");
        // 判断余量沿用标识是否为空
        String useReuse;
        if (StringUtils.isEmpty(oldNurseRecordForm.getUseReuse()))
            useReuse = IN_OUT_AMOUNT_USE_SURPLUS;
        else if (StringUtils.equals(oldNurseRecordForm.getUseReuse(), IN_OUT_AMOUNT_USE_ALL_ALLOWANCE_DOSAGE))
            useReuse = IN_OUT_AMOUNT_USE_SURPLUS_ALL_ALLOWANCE_DOSAGE;
        else
            return new HttpResult(500, "沿用旧的状态标识错误");
        String newMedicineContent = oldNurseRecordForm.getMedicineContent();
        oldNurseRecordForm.setUseReuse(useReuse);
        oldNurseRecordForm.setMedicineContent("(已沿用)" + oldNurseRecordForm.getMedicineContent());
        // 修改旧的标识状态
        update(oldNurseRecordForm);
        // 新增新的沿用数据
        oldNurseRecordForm.setMedicineContent(newMedicineContent);
        //新增数据
        saveNewUseForm(oldNurseRecordForm, nurseRecordForm.getDataTime(), user);
        return new HttpResult(200, "沿用成功");
    }

    /**
     * 沿用生成新的一条数据
     * 添加生命体征和填充数据
     *
     * @param oldNurseRecordForm
     */
    private void saveNewUseForm(NurseRecordForm oldNurseRecordForm, Date dateTime, User user) throws ParseException {
        NurseRecordForm nurseRecordForm = new NurseRecordForm();
        nurseRecordForm.setId(getUUID());
        //去除填充的备用量不破坏原有逻辑
        if (!USER_FULL_DATA_FLAG) {
            nurseRecordForm.setReserveAmount(oldNurseRecordForm.getSurplus());
        }
        nurseRecordForm.setUseReuse(IN_OUT_AMOUNT_USE_ALL_ALLOWANCE_DOSAGE);
        if (oldNurseRecordForm.getMedicineContent().contains("沿用上次余量"))
            nurseRecordForm.setMedicineContent(oldNurseRecordForm.getMedicineContent());
        else
            nurseRecordForm.setMedicineContent(oldNurseRecordForm.getMedicineContent() + "（沿用上次余量）");
        nurseRecordForm.setVisitId(oldNurseRecordForm.getVisitId());
        nurseRecordForm.setVisitCode(oldNurseRecordForm.getVisitCode());
        nurseRecordForm.setPatientId(oldNurseRecordForm.getPatientId());
        nurseRecordForm.setParentId(oldNurseRecordForm.getId());
        nurseRecordForm.setDataTime(dateTime);
        nurseRecordForm.setCreateTime(new Date());
        nurseRecordForm.setStatus(1);
        //需要填充的数据不破坏原有逻辑
        if (USER_FULL_DATA_FLAG) {
            setOldInvariantNurseRecordFormData(nurseRecordForm, nurseRecordForm.getDataTime(), 1);
        }
        insert(nurseRecordForm);
    }

    /**
     * 查询是否可以进行修改出入量数据
     *
     * @param map
     * @return
     */
    public HttpResult isUpdateData(Map<String, Object> map) {
        try {
            errorIfEmpty(map, "参数不能为空");
            errorIfEmpty(map.get("parent_id"), "父级id不能为空");
            long count = nurseRecordFormDao.selectCount(getParamOne("parent_id", map.get("parent_id"), "1"));
            if (count > 0)
                return new HttpResult(200, "false");
            return new HttpResult(200, "true");
        } catch (Exception e) {
            return new HttpResult(500, e.getMessage());
        }
    }

    /**
     * 接班获取最新数据
     *
     * @param map
     * @param session
     * @return
     */
    public HttpResult isCarryData(Map<String, Object> map, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            errorIfEmpty(map, "参数不存在");
            errorIfEmpty(map.get("patientId"), "患者id不能为空");
            errorIfEmpty(map.get("dataTime"), "数据时间不能为空");
            boolean timeChange = map.get("timeChange")==null?false:true;
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("patientId", map.get("patientId"));
            paramMap.put("endTime", map.get("dataTime"));
            paramMap.put("flag", "flag");
            //查询是否交班，交班返回空
            NurseRecordForm nurseRecordForm = nurseRecordFormDao.queryByPatientAndDataTime(paramMap);
            //赋值新的插入数据
            Patient patient = patientDao.queryData(map.get("patientId").toString());
            String dataTime = map.get("dataTime").toString();
            Date date = yyyyMMddHHmmssSdfToDate(dataTime);
            //新增的数据
            NurseRecordForm nurseRecordFormNew = new NurseRecordForm();
            nurseRecordFormNew.setDataTime(date);
            nurseRecordFormNew.setDate(yyyyMMddSdfToString(date));
            nurseRecordFormNew.setTime(hhmmSdfToString(date));
            nurseRecordFormNew.setPatientId(map.get("patientId").toString());
            nurseRecordFormNew.setTimeChange(timeChange);
            Boolean flag = false;
            //判断是否交班
            if (nurseRecordForm != null && isNotEmpty(nurseRecordForm.getSecondSign()) ) {
                flag = true;
            }
            setNewNurseRecordFormData(nurseRecordFormNew, user, 1);
            //insert(nurseRecordFormNew);
            resultMap.put("flag",flag);
            resultMap.put("data",nurseRecordFormNew);
            return new HttpResult(200, resultMap, flag?"最新数据已接班":"最新数据未接班");
        } catch (Exception e) {
            resultMap.put("flag",null);
            resultMap.put("data",null);
            return new HttpResult(500, resultMap, e.getMessage());
        }
    }

    /**
     * 查询最新数据并赋值新的生命体征
     *
     * @param map
     * @return
     */
    public HttpResult getNewData(Map<String, Object> map) {
        try {
            errorIfEmpty(map, "参数不存在");
            errorIfEmpty(map.get("patientId"), "患者id不能为空");
            errorIfEmpty(map.get("dataTime"), "数据时间不能为空");
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("patientId", map.get("patientId").toString());
            paramMap.put("dataTime", map.get("dataTime").toString());
            NurseRecordForm newNurseRecordForm = new NurseRecordForm();
            Patient patient = patientDao.queryData(map.get("patientId").toString());
            //获取最新的生命体征数据
            boolean isOpenPulseRecord = getIsOpenPulseRecord(patient);
            //查询最新一条数据的填充数据
            NurseRecordForm nurseRecordForm = nurseRecordFormDao.queryByPatientAndDataTime(paramMap);

            newNurseRecordForm.setConsciousness(nurseRecordForm.getConsciousness()); // 意识
            //newNurseRecordForm.setDragFlag(nurseRecordForm.getDragFlag()); // 是否使用药物
            newNurseRecordForm.setPupilSizeLeft(nurseRecordForm.getPupilSizeLeft()); // 瞳孔大小左
            newNurseRecordForm.setPupilSizeRight(nurseRecordForm.getPupilSizeRight());// 瞳孔大小右
            newNurseRecordForm.setPupilResponseLeft(nurseRecordForm.getPupilResponseLeft()); // 瞳孔反应左
            newNurseRecordForm.setPupilResponseRight(nurseRecordForm.getPupilResponseRight()); // 瞳孔反应右
            newNurseRecordForm.setHeartRhythm(nurseRecordForm.getHeartRhythm()); // 心律

            newNurseRecordForm.setOxygenMode(nurseRecordForm.getOxygenMode()); // 吸氧方式
            newNurseRecordForm.setFio2(nurseRecordForm.getFio2()); // fio2
            newNurseRecordForm.setOxygenFlow(nurseRecordForm.getOxygenFlow()); // 氧流量
            newNurseRecordForm.setMode(nurseRecordForm.getMode());
            newNurseRecordForm.setVt(nurseRecordForm.getVt());
            newNurseRecordForm.setF(nurseRecordForm.getF());
            newNurseRecordForm.setPinsp(nurseRecordForm.getPinsp());
            newNurseRecordForm.setPs(nurseRecordForm.getPs());
            newNurseRecordForm.setPeep(nurseRecordForm.getPeep());
            newNurseRecordForm.setIpap(nurseRecordForm.getIpap());
            newNurseRecordForm.setEpap(nurseRecordForm.getEpap());
            newNurseRecordForm.setNurseActivity(nurseRecordForm.getNurseActivity()); // 护理活动（活动/翻身/卧位）
            newNurseRecordForm.setPipeNurse(nurseRecordForm.getPipeNurse()); // 导管/护理
            newNurseRecordForm.setStomachTubeLength(nurseRecordForm.getStomachTubeLength()); //胃管长度
            newNurseRecordForm.setStomachTubeUnobstructed(nurseRecordForm.getStomachTubeUnobstructed()); // 胃管是否通畅
            newNurseRecordForm.setNasointestinalTubeLength(nurseRecordForm.getNasointestinalTubeLength()); // 鼻肠管长度
            newNurseRecordForm.setNasointestinalTubeUnobstructed(nurseRecordForm.getNasointestinalTubeUnobstructed()); // 鼻肠管是否通畅
            newNurseRecordForm.setNurseMeasure(nurseRecordForm.getNurseMeasure()); //  护理措施
            newNurseRecordForm.setNurseSkin(nurseRecordForm.getNurseSkin()); //护理皮肤
            errorIfEmpty(nurseRecordForm, "患者三表合一数据不存在");
            if (isNotEmpty(nurseRecordForm.getSecondSign()))
                return new HttpResult(200, "true", "最新数据已接班");
            return new HttpResult(200, "false", "最新数据未接班");
        } catch (Exception e) {
            return new HttpResult(500, "false", e.getMessage());
        }
    }

    private String setValue(String oldValue, String newValue) {
        if (org.apache.commons.lang.StringUtils.isEmpty(oldValue))
            return newValue;
        return oldValue;
    }

    /**
     * 通过最新的一条生命体征数据和上一条数据
     */
    public void setNewNurseRecordFormData(NurseRecordForm nurseRecordForm, User user, int flag) throws ParseException {
        //通过时间和患者id查询最新一条数据
        String dateTime = yyyyMMddHHmmssSdfToString(nurseRecordForm.getDataTime());
        String patientId = nurseRecordForm.getPatientId();
        Patient patient = patientDao.queryData(patientId);
        boolean isOpenPulseRecord = getIsOpenPulseRecord(patient);
        //赋值最新的生命体征数据
        MonitorLifeData monitorLifeData = vitalSignMergeService.findMonitorLifeData(dateTime, nurseRecordForm.getPatientId());
        if (monitorLifeData != null) {
            setNurseRecordForm(nurseRecordForm, monitorLifeData, isOpenPulseRecord, user);
        }
        //赋值上一条填充的数据
        //if (flag != 1 ) {
            setOldInvariantNurseRecordFormData(nurseRecordForm, nurseRecordForm.getDataTime(), flag);
       // }
        setBreathProperty(nurseRecordForm, patient);
    }

    private void setBreathProperty(NurseRecordForm nurseRecordForm, Patient patient) {
        BreathProperty breathProperty = mongodbService.getBreathProperty(patient, nurseRecordForm.getDataTime(), null);
        if(Objects.nonNull(breathProperty)){
            if(StringUtils.isNotBlank(breathProperty.getPeep())){
                nurseRecordForm.setPeep(breathProperty.getPeep());
            }
            if(StringUtils.isNotBlank(breathProperty.getVt())){
                nurseRecordForm.setVt(breathProperty.getVt());
            }
            if(StringUtils.isNotBlank(breathProperty.getFio2())){
                nurseRecordForm.setFio2(breathProperty.getFio2());
            }
            if(StringUtils.isNotBlank(breathProperty.getF())){
                nurseRecordForm.setF(breathProperty.getF());
            }
            if(StringUtils.isNotBlank(breathProperty.getIpap())){
                nurseRecordForm.setIpap(breathProperty.getIpap());
            }
            if(StringUtils.isNotBlank(breathProperty.getEpap())){
                nurseRecordForm.setEpap(breathProperty.getEpap());
            }
            if(StringUtils.isNotBlank(breathProperty.getPs())){
                nurseRecordForm.setPs(breathProperty.getPs());
            }
            if(StringUtils.isNotBlank(breathProperty.getPinsp())){
                nurseRecordForm.setPinsp(breathProperty.getPinsp());
            }
        }
    }

    public void saveAutoGeneratedData(NursingTaskDTO nursingTaskDTO) {
        Date dataTime = nursingTaskDTO.getDataTime();
        String patientId = nursingTaskDTO.getPatientId();
        NurseRecordForm nurseRecordForm = new NurseRecordForm();
        nurseRecordForm.setPatientId(patientId);
        nurseRecordForm.setId(getUUID());
        nurseRecordForm.setStatus(1);
        if (StringUtils.equals(nursingTaskDTO.getNursingCategories(), "turn_over")) {
            nurseRecordForm.setNurseActivity(nursingTaskDTO.getNursingType());
        }
        if (StringUtils.equals(nursingTaskDTO.getNursingCategories(), "nurseMeasure")) {
            nurseRecordForm.setNurseMeasure(nursingTaskDTO.getNursingType());
        }
        if (StringUtils.equals(nursingTaskDTO.getNursingCategories(), "ulcerCare")) {
            nurseRecordForm.setNurseSkin(nursingTaskDTO.getNursingType());
        }
        nurseRecordForm.setDataTime(dataTime);
        nurseRecordForm.setDataSource(2);
        if (StringUtils.isAllBlank(nurseRecordForm.getNurseActivity(), nurseRecordForm.getNurseMeasure(), nurseRecordForm.getNurseSkin())) {
            logger.error("护理单自动生成护理数据，护理数据都为空,nursingTaskDTO:{}", JSON.toJSONString(nursingTaskDTO));
            return;
        }
        //根据患者id时间和类型查询护理单记录
        Map<String, Object> map = new HashMap<>();
        map.put("patientId", patientId);
        map.put("dataTime", DateUtil.yyyyMMddHHmmSdfToString(dataTime));
        map.put("dataSource", 2);
        map.put("status", 1);
        NurseRecordForm fromDb = nurseRecordFormDao.queryByPatientAndDataTime(map);

        if (Objects.nonNull(fromDb)) {
            //update 数据
            nurseRecordForm.setId(fromDb.getId());
            if(StringUtils.isNotEmpty(fromDb.getNurseMeasure()) && StringUtils.isNotEmpty(nurseRecordForm.getNurseMeasure())){
                if(fromDb.getNurseMeasure().contains(nurseRecordForm.getNurseMeasure())) {
                    nurseRecordForm.setNurseMeasure(null);
                }
            }

            if(StringUtils.isNotEmpty(fromDb.getNurseActivity()) && StringUtils.isNotEmpty(nurseRecordForm.getNurseActivity())){
                if(fromDb.getNurseActivity().contains(nurseRecordForm.getNurseActivity())) {
                    nurseRecordForm.setNurseActivity(null);
                }
            }

            if(StringUtils.isNotEmpty(fromDb.getNurseSkin()) && StringUtils.isNotEmpty(nurseRecordForm.getNurseSkin())){
                if(fromDb.getNurseSkin().contains(nurseRecordForm.getNurseSkin())) {
                    nurseRecordForm.setNurseSkin(null);
                }
            }

            if(!StringUtils.isAllEmpty(nurseRecordForm.getNurseMeasure(),nurseRecordForm.getNurseActivity(),nurseRecordForm.getNurseSkin())) {
                nurseRecordFormDao.updateCareInfo(nurseRecordForm);
            }

            return;
        }
        /**
         * 添加保存生命体征和护理延续的数据
         */
        try {
            setNewNurseRecordFormData(nurseRecordForm, null, 1);
        }catch (Exception e){
            logger.error(e.getMessage());
        }

        //insert
        insert(nurseRecordForm);
    }

    public HttpResult queryListV2(Map<String, Object> map) {
//        if (!map.containsKey("hour")) {
//            return new HttpResult(200, "查询时间跨度小时为空，查询失败");
//        }
        try {
//            Date endTime = getLaterHoursDate(yyyyMMddHHmmssSdfToDate(String.valueOf(map.get("startTime"))), Long.valueOf(String.valueOf(map.get("hour"))));
//            map.put("endTime", yyyyMMddHHmmssSdfToString(endTime));
            List<NurseRecordForm> list = nurseRecordFormDao.queryList(map);

            if (CollectionUtil.isEmpty(list)) {
                return new HttpResult(200, list, 0, "数据查询成功");
            }

            if(list.size()==1){
                return new HttpResult(200, list, list.size(), "查询数据成功");
            }

            List<NurseRecordForm> resultList = new ArrayList<>();
            List<NurseRecordForm> tempList = new ArrayList<>();
            Date dataTimeTemp = null;
            for (int i = 0; i < list.size(); i++) {
                NurseRecordForm nurseRecordForm = list.get(i);
                Date dataTime = nurseRecordForm.getDataTime();

                if (dataTimeTemp == null) {
                    tempList.add(nurseRecordForm);
                    dataTimeTemp = dataTime;
                    continue;
                }

                if (dataTimeTemp.equals(dataTime)) {
                    tempList.add(nurseRecordForm);
                    if (i + 1 == list.size()) {
                        dealTempList(tempList, resultList);
                        tempList = new ArrayList<>();
                    }
                    continue;
                }

                dealTempList(tempList, resultList);
                tempList = new ArrayList<>();
                tempList.add(nurseRecordForm);
                dataTimeTemp = dataTime;
                if (i + 1 == list.size()) {
                    dealTempList(tempList, resultList);
                    break;
                }
            }
            return new HttpResult(200, resultList, resultList.size(), "数据查询成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HttpResult(500, "数据查询失败");
    }

    private void dealTempList(List<NurseRecordForm> tempList, List<NurseRecordForm> resultList) {
        if (CollectionUtil.isEmpty(tempList)) {
            return;
        }
        if (tempList.size() == 1) {
            resultList.addAll(tempList);
            return;
        }

        //如果全部为人工添加数据，直接添加返回
        // 如果存在自动生成数据，则判断人工数据是否护理和监护仪字段为空，自动生成的数据赋值，remove自动生成数据
        List<NurseRecordForm> manualList = tempList.stream().filter(nurseRecordForm -> 0 == nurseRecordForm.getDataSource()).collect(Collectors.toList());
        List<NurseRecordForm> autoList = tempList.stream().filter(nurseRecordForm -> 0 != nurseRecordForm.getDataSource()).collect(Collectors.toList());

        if (CollectionUtil.isEmpty(autoList)) {
            resultList.addAll(tempList);
            return;
        }

        List<NurseRecordForm> auto1List = autoList.stream().filter(nurseRecordForm -> 2 != nurseRecordForm.getDataSource()).collect(Collectors.toList());
        List<NurseRecordForm> auto2List = autoList.stream().filter(nurseRecordForm -> 2 == nurseRecordForm.getDataSource()).collect(Collectors.toList());
        NurseRecordForm auto2 = null;

        if(CollectionUtil.isNotEmpty(auto2List)){
            Set<String> nurseActivitySet = new HashSet<>();
            Set<String> nurseMeasureSet = new HashSet<>();
            Set<String> nurseSkinSet = new HashSet<>();
            for (NurseRecordForm auto:auto2List) {
                if (StringUtils.isNotBlank(auto.getNurseActivity())) {
                    nurseActivitySet.addAll(Arrays.asList(auto.getNurseActivity().split(",")));
                }
                if (StringUtils.isNotBlank(auto.getNurseMeasure())) {
                    nurseMeasureSet.addAll(Arrays.asList(auto.getNurseMeasure().split(",")));
                }
                if (StringUtils.isNotBlank(auto.getNurseSkin())) {
                    nurseSkinSet.addAll(Arrays.asList(auto.getNurseSkin().split(",")));
                }
            }
            auto2 = auto2List.get(0);
            auto2.setNurseActivity(nurseActivitySet.size()>0? Joiner.on(",").join(nurseActivitySet):"");
            auto2.setNurseMeasure(nurseMeasureSet.size()>0? Joiner.on(",").join(nurseMeasureSet):"");
            auto2.setNurseSkin(nurseActivitySet.size()>0? Joiner.on(",").join(nurseSkinSet):"");
        }

        if(CollectionUtil.isEmpty(manualList)){
            if(CollectionUtil.isNotEmpty(auto1List)){
                for (NurseRecordForm auto1 : auto1List) {
                    if(auto2!=null) {
                        auto1.setNurseActivity(auto2.getNurseActivity());
                        auto1.setNurseMeasure(auto2.getNurseMeasure());
                        auto1.setNurseSkin(auto2.getNurseSkin());
                    }
                }
                resultList.addAll(auto1List);
            }
            if(Objects.nonNull(auto2) && CollectionUtil.isEmpty(resultList)){
                resultList.add(auto2);
            }
            return;
        }

        //判断手动数据是否全部为小结总结
        if(manualList.stream().allMatch(nurseRecordForm -> StringUtils.equalsAny(nurseRecordForm.getFlag(), "小结", "总结"))){
            resultList.addAll(manualList);
            if(CollectionUtil.isNotEmpty(auto1List)){
                resultList.addAll(auto1List);
            }
            if(Objects.nonNull(auto2)){
                resultList.add(auto2);
            }
            return;
        }

        if(Objects.nonNull(auto2)){
            for (NurseRecordForm manual : manualList) {
                if(StringUtils.equalsAny(manual.getFlag(), "小结","总结")){
                    continue;
                }
                if(StringUtils.isBlank(manual.getNurseActivity())){
                    manual.setNurseActivity(auto2.getNurseActivity());
                }
                if(StringUtils.isBlank(manual.getNurseMeasure())){
                    manual.setNurseMeasure(auto2.getNurseMeasure());
                }
                if(StringUtils.isBlank(manual.getNurseSkin())){
                    manual.setNurseSkin(auto2.getNurseSkin());
                }
            }
        }
        resultList.addAll(manualList);
    }

    /**
     * 获取患者观察项指标数据 【每小时一条】
     * @param map
     * @return
     */
    public List<VitalSignsStatisticDataDTO> statisticVitalSigns(Map<String, Object> map) {
        List<VitalSignsStatisticDataDTO> list = nurseRecordFormDao.statisticVitalSigns(map);
        if(CollectionUtil.isEmpty(list)){
            return Lists.newArrayList();
        }

        if(list.size()==1){
            return list;
        }

        List<VitalSignsStatisticDataDTO> resultList = new ArrayList<>();
        List<VitalSignsStatisticDataDTO> tempList = new ArrayList<>();
        String dataTimeTemp = null;
        for (int i = 0; i < list.size(); i++) {
            VitalSignsStatisticDataDTO data = list.get(i);
            String dataTime = data.getDataTime();

            if (dataTimeTemp == null) {
                tempList.add(data);
                dataTimeTemp = dataTime;
                continue;
            }

            if (dataTimeTemp.equals(dataTime)) {
                tempList.add(data);
                if (i + 1 == list.size()) {
                    dealStatistic(tempList, resultList);
                    tempList = new ArrayList<>();
                }
                continue;
            }

            dealStatistic(tempList, resultList);
            tempList = new ArrayList<>();
            tempList.add(data);
            dataTimeTemp = dataTime;
            if (i + 1 == list.size()) {
                dealStatistic(tempList, resultList);
                break;
            }
        }
        return resultList;
    }

    /**
     * 合并患者观察项生命体征数据【每小时保留一条】
     * @param tempList
     * @param resultList
     */
    private void dealStatistic(List<VitalSignsStatisticDataDTO> tempList, List<VitalSignsStatisticDataDTO> resultList) {
        if(CollectionUtil.isEmpty(tempList)){
            return;
        }
        if(tempList.size()==1){
            resultList.add(tempList.get(0));
            return;
        }

        List<VitalSignsStatisticDataDTO> manualList = tempList.stream().filter(data -> 0 == data.getDataSource()).collect(Collectors.toList());
        List<VitalSignsStatisticDataDTO> autoList = tempList.stream().filter(data -> 0 != data.getDataSource()).collect(Collectors.toList());

        if(CollectionUtil.isEmpty(manualList) || CollectionUtil.isEmpty(autoList)){
            resultList.add(CollectionUtil.isEmpty(manualList)?autoList.get(0):manualList.get(0));
            return;
        }

        VitalSignsStatisticDataDTO data = manualList.get(0);
        for (VitalSignsStatisticDataDTO auto : autoList) {
            if(StringUtils.isBlank(data.getAbp())){
                data.setAbp(auto.getAbp());
            }
            if(StringUtils.isBlank(data.getNbp())){
                data.setNbp(auto.getNbp());
            }
            if(StringUtils.isBlank(data.getTemplate())){
                data.setTemplate(auto.getTemplate());
            }
            if(StringUtils.isBlank(data.getBloodGlucose())){
                data.setBloodGlucose(auto.getBloodGlucose());
            }
            if(StringUtils.isBlank(data.getHr())){
                data.setHr(auto.getHr());
            }
        }
        resultList.add(data);
    }

    /**
     * 批量修改时间范围内护理单字段内容
     * @param map
     * @return
     */
    public HttpResult batchUpdateField(Map<String, Object> map, HttpSession session) {
        errorIfEmpty(map.get("fieldName"), "字段名称不能为空");
        errorIfEmpty(map.get("patientId"), "患者id不能为空");
        errorIfEmpty(map.get("startTime"), "开始时间不能为空");
        errorIfEmpty(map.get("endTime"), "结束时间不能为空");
//        User user = (User) session.getAttribute("user");
//        if(user == null || StringUtils.isEmpty(user.getRoleId())){
//            return new HttpResult(500,"系统错误");
//        }
//
//        Role role = roleDao.queryData(user.getRoleId());
//        if(role == null || !StringUtils.containsAny(role.getRoleName(),"超级管理员","护士长")){
//            Patient patient = patientDao.queryData(map.get("patientId").toString());
//            if(patient == null || 1 != patient.getStatus()||  1 != patient.getFlag()){
//                return new HttpResult(500,"数据修改失败,患者已出科");
//            }
//        }
        if(!FIELD_LIST.contains(map.get("fieldName").toString())){
            return new HttpResult(500,"当前列不能批量修改");
        }

        if(!map.containsKey("fieldValue")){
            throw new JyxdException("字段值不能为空");
        }

        map.put("tableField",toUnderScoreCase(map.get("fieldName").toString()));

        List<String> list = nurseRecordFormDao.getFieldList(map);
        Set<String> set = new HashSet<>();
        list.forEach(fieldValue->{
            if(StringUtils.isNotEmpty(fieldValue)){
                set.add(fieldValue);
            }
        });
        if(set.size()>1){
            return new HttpResult(500,"数据不一致，数据修改失败");
        }

        int update = nurseRecordFormDao.batchUpdateField(map);
        return new HttpResult(200, update,"数据修改成功");
    }

    /**
     * 下划线转驼峰命名
     */
    public static String toUnderScoreCase(String str) {
        if (str == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        // 前置字符是否大写
        boolean preCharIsUpperCase = true;
        // 当前字符是否大写
        boolean curreCharIsUpperCase = true;
        // 下一字符是否大写
        boolean nexteCharIsUpperCase = true;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (i > 0) {
                preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
            } else {
                preCharIsUpperCase = false;
            }

            curreCharIsUpperCase = Character.isUpperCase(c);

            if (i < (str.length() - 1)) {
                nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
            }

            if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
                sb.append("_");
            } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
                sb.append("_");
            }
            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }


    public HttpResult batchUpdateFieldCheck(Map<String, Object> map) {
        errorIfEmpty(map.get("fieldName"), "字段名称不能为空");
        errorIfEmpty(map.get("patientId"), "患者id不能为空");
        errorIfEmpty(map.get("startTime"), "开始时间不能为空");
        errorIfEmpty(map.get("endTime"), "结束时间不能为空");
        if(!FIELD_LIST.contains(map.get("fieldName").toString())){
            return new HttpResult(500,"当前列不能批量修改");
        }

        map.put("tableField",toUnderScoreCase(map.get("fieldName").toString()));

        List<String> list = nurseRecordFormDao.getFieldList(map);
        Set<String> set = new HashSet<>();
        list.forEach(fieldValue->{
            if(StringUtils.isNotEmpty(fieldValue)){
                set.add(fieldValue);
            }
        });
        if(set.size()>1){
            return new HttpResult(500,"数据不一致，不可以批量修改");
        }
        return new HttpResult(200,"数据一致，可以批量修改");
    }
}
